package com.sofian.chat.server;

import java.util.ArrayList;
import java.util.Date;

import org.restlet.resource.Get;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;

import com.sofian.chat.client.ChatMessage;
import com.sofian.chat.client.ChatMessageService;

public class ChatResource extends ServerResource {

	private static ArrayList<ChatMessage> messages = MessageShare.getMessages();
	
	@Get
	public ChatMessage[] getNewMessages() {
		
	
		
		
		 long since = Long.valueOf(  this.getRequest().getResourceRef().getQueryAsForm().getFirstValue("time")); 
		synchronized(messages) {
			int index = messages.size() - 1;
			int count = 0;
			while(index >= 0) {
				if(messages.get(index).getTimestamp() > since) {
					count++;
					index--;
				} else {
					break;
				}
			}
			ChatMessage[] array = new ChatMessage[0];
			if(count > 0) {
				return messages.subList(messages.size() - count, messages.size()).toArray(array);
			} else {
				return array;
			}
			
		}
	}
	
	
	
	@Put
	public void sendMessage(String sender, String message) {
		messages.add(new ChatMessage(new Date().getTime(),sender, message));
		MessageShare.addMessages(messages);
		
	}
	
	

	
	
	}
